from infoUi import wx
from infoUi import myInfoUi
from infoUi import os
from infoUi import threading
import zipfile

out_path=os.path.join(os.getcwd(),"out")
tool_path=os.path.join(os.getcwd(),"tools")

def unzipImg(filename,unzip_path):
    with zipfile.ZipFile(filename) as z:
        for f in z.namelist():
            if f == "system.img":
                z.extract(f,unzip_path)
                path=os.path.join(unzip_path,"system.img")
                return path

def mkDiff(mainUi,src,dst):
    print(src)
    print(dst)
    outZipSrc=os.path.join(out_path,"src.img")
    outZipDst=os.path.join(out_path,"dst.img")
    #获取src.img
    unzipFile=unzipImg(src,out_path)
    print("outpath:"+unzipFile)
    if(os.path.exists(unzipFile)):
        if(os.path.exists(outZipSrc)):
            os.remove(outZipSrc)
        os.rename(unzipFile, outZipSrc)
    #获取dst.img
    unzipFile=unzipImg(dst,out_path)
    if(os.path.exists(unzipFile)):
        if(os.path.exists(outZipDst)):
            os.remove(outZipDst)
        os.rename(unzipFile, outZipDst)


    adiffScript=os.path.join(tool_path,"mkAdiff.bat")
    #制作升级包
    r_v=os.system(adiffScript+" "+out_path+" "+out_path)
    if(r_v == 0):
        #mainUi.infoUiCtr['InfoText'].AppendText("执行成功!\r\n")
        pass
    else:
        #mainUi.infoUiCtr['InfoText'].AppendText("执行失败!\r\n")
        pass

def delDiff():
    for path,dirs,files in os.walk(out_path):
        for file in files:
            if(os.path.splitext(file)[1] == '.bin' or os.path.splitext(file)[1] == '.img'):
                os.remove(os.path.join(path, file))


class myAdiffUi(myInfoUi):

    def __init__(self, parent=None, title="MyTest",pos = (1000,680),size = (1024,600)):
        wx.Frame.__init__(self,parent=parent, title=title,size=size)
        self.panel = wx.Panel(self,size = (1024,600))

    def setUpAdiffUi(self):
        self.__adiffThread = threading.Thread(target=mkDiff, name='adiff', daemon=True)
        self.adiffUiCtr = {
            'adiffSrc':'',
            'adiffDst':'',
            'BoxSizer':'',
        }
    #差分组件
        sAdiff_box = wx.StaticBox(self.panel, -1, "Adiff tool")
        self.adiffUiCtr['BoxSizer'] = wx.StaticBoxSizer(sAdiff_box,wx.VERTICAL)
        src_box = wx.BoxSizer(wx.HORIZONTAL)
        dst_box = wx.BoxSizer(wx.HORIZONTAL)
        adiffBtn_box = wx.BoxSizer(wx.HORIZONTAL)

        #src file box
        srcFile_label = wx.StaticText(self.panel,label = "源文件:",size=(60,-1))
        self.adiffUiCtr['adiffSrc'] = wx.TextCtrl(self.panel,wx.ALIGN_LEFT,size=(-1,25))
        srcFile_button = wx.Button(self.panel,label = "浏览",size=(40,-1))
        src_box.Add(srcFile_label,proportion = 0)
        src_box.Add(self.adiffUiCtr['adiffSrc'],proportion = 4,flag = wx.EXPAND|wx.ALL,border = 3)
        src_box.Add(srcFile_button,proportion = 1,flag = wx.ALL,border = 3)

        #dst file box
        dstFile_label = wx.StaticText(self.panel,label = "目标文件:",size=(60,-1))
        self.adiffUiCtr['adiffDst'] = wx.TextCtrl(self.panel,wx.ALIGN_LEFT,size=(-1,25))
        dstFile_button = wx.Button(self.panel,label = "浏览",size=(40,-1))
        dst_box.Add(dstFile_label,proportion = 0)
        dst_box.Add(self.adiffUiCtr['adiffDst'],proportion = 4,flag = wx.EXPAND|wx.ALL,border = 3)
        dst_box.Add(dstFile_button,proportion = 1,flag = wx.ALL,border = 3)

        #adiff button
        mk_button = wx.Button(self.panel,label = "生成")
        del_button = wx.Button(self.panel,label = "删除")
        adiffBtn_box.Add(mk_button,proportion = 1,flag = wx.ALL,border = 3)
        adiffBtn_box.Add(del_button,proportion = 1,flag = wx.ALL,border = 3)

        #差分包制作组件布局
        self.adiffUiCtr['BoxSizer'].Add(src_box,proportion = 0,flag = wx.EXPAND|wx.ALL,border = 3)
        self.adiffUiCtr['BoxSizer'].Add(dst_box,proportion = 0,flag =  wx.EXPAND|wx.ALL,border = 3)
        self.adiffUiCtr['BoxSizer'].Add(adiffBtn_box,proportion = 0,flag = wx.EXPAND|wx.ALL,border = 3)

        #事件绑定
        srcFile_button.Bind(wx.EVT_BUTTON, self.onSrcfile)
        dstFile_button.Bind(wx.EVT_BUTTON, self.onDstfile)
        mk_button.Bind(wx.EVT_BUTTON, self.onMkFotaPkg)
        del_button.Bind(wx.EVT_BUTTON, self.onDelFotaPkg)

        #debug size
        #print(srcFile_button.size)

    def onSrcfile(self,evt):
        wildcard = "Files (*.*)|*.zip"
        '''
        strPath = self.adiffUiCtr['adiffSrc'].GetValue()
        if(strPath == ''):
            path = os.getcwd()
        else:
            path = ('\\'.join(str(strPath).split('\\')[:-1]))
            pass
        dlg = wx.FileDialog(self, "Choose a file", path, "", wildcard, wx.FLP_OPEN)
        '''
        dlg = wx.FileDialog(self, "Choose a file", os.getcwd(), "", wildcard, wx.FLP_OPEN)
        if dlg.ShowModal() == wx.ID_OK:
            fPath = dlg.GetPath()
            self.adiffUiCtr['adiffSrc'].SetValue(fPath)

    def onDstfile(self,evt):
        wildcard = "Files (*.*)|*.zip"
        dlg = wx.FileDialog(self, "Choose a file", os.getcwd(), "", wildcard, wx.FLP_OPEN)
        if dlg.ShowModal() == wx.ID_OK:
            fPath = dlg.GetPath()
            self.adiffUiCtr['adiffDst'].SetValue(fPath)

    def onMkFotaPkg(self,evt):
        srcfile=self.adiffUiCtr['adiffSrc'].GetValue()
        dstfile=self.adiffUiCtr['adiffDst'].GetValue()

        if(len(srcfile) != 0 and len(dstfile) != 0):
                if(self.__adiffThread.is_alive() == False):
                    self.__adiffThread = threading.Thread(target=mkDiff, name='adiff', daemon=True,args=(self,srcfile,dstfile))
                    self.__adiffThread.start()
                else:
                    self.errorDebug("adiff service is run!\r\n")
        else:
            self.errorDebug("need two file\r\n")

    def onDelFotaPkg(self,evt):
            delDiff()
            self.warningDebug("delete file *.bin *.img\r\n")


#adiffUi demo
if __name__ == '__main__':
    app = wx.App()
    frame = myAdiffUi(title="While there is life,there is hope.")
    frame.setUpInfoUi()
    frame.setUpAdiffUi()
    mainBox = wx.BoxSizer()
    mainBox.Add(frame.infoUiCtr['BoxSizer'],proportion = 1,flag=wx.EXPAND|wx.ALL,border = 3)
    mainBox.Add(frame.adiffUiCtr['BoxSizer'],proportion = 0,flag=wx.EXPAND|wx.ALL,border = 3)
    frame.panel.SetSizer(mainBox)
    frame.Show()
    app.MainLoop()
